package com.ithiema.EmployeeListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.ithiema.dao.EmployeeDao;
import com.ithiema.pojo.Employee;

import java.util.ArrayList;

/*
    自定义监听器读数据
 */
public class EmployeeListener implements ReadListener<Employee> {

    private int count = 100;
    private ArrayList<Employee> list = new ArrayList<>(count);
    private EmployeeDao dao;

    public EmployeeListener(EmployeeDao dao) {
        this.dao = dao;
    }

    // 每读一行数据,都会调用这个方法
    @Override
    public void invoke(Employee employee, AnalysisContext analysisContext) {
        // 将读取到的一行数据添加到集合
        list.add(employee);
        // 判断是不是到达缓存量了
        if(list.size()>=100){
            // 操作数据库
            dao.save(list);
            list= new ArrayList<>(count);
        }
    }

    // 读完整个excel之后,会调用这个方法
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if(list.size()>0){
            // 操作数据库
            dao.save(list);
            list= new ArrayList<>(count);
        }
    }
}
